/*
 * @Date: 2021-11-16 20:11:58
 * @Version: 1.0.0
 * @Author: chenhengling
 * @Description: 解析git配置文件
 * @LastEditTime: 2021-11-17 09:34:10
 * @LastEditors: chenhengling
 */
const fs = require('fs');
const os = require('os');
const path = require('path');
const ini = require('ini');

function getPath(type) {
  let configPath = '';
  const workDir = process.cwd();

  if (type === 'global') {
    configPath = path.join(os.homedir(), '.gitconfig');
  } else {
    configPath = path.resolve(workDir, '.git/config');
  }

  if (!fs.existsSync(configPath)) {
    configPath = path.join(os.homedir(), '.config/git/config');
  }

  return fs.existsSync(configPath) ? configPath : null;
}

function main(type) {
  const configPath = getPath(type);
  if (configPath) {
    const file = fs.readFileSync(configPath, 'utf8');
    return ini.parse(file);
  }
  return null;
}

module.exports = main;

if (require.main === module) {
  console.log(main('global'));
}
